package middleware

import (
	"ser1/database"
	"ser1/redisdb"
	"ser1/utils"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func DB() *gorm.DB {
	return database.GetDB()
}

// Middleware 中间件函数
/**
 * @Description: 中间件函数
 * @param routePath 排除的路由
 * @return gin.HandlerFunc
 */
func Middleware(routePath ...string) gin.HandlerFunc {

	return func(c *gin.Context) {
		// 获取当前请求的路径
		currentPath := c.Request.URL.Path
		skip := false
		for _, path := range routePath {
			//如果路由包含，跳过
			if utils.StrContains(currentPath, path) {
				skip = true
				break
			}
		}
		if skip {
			c.Next()
			return
		}

		// 获取用户Token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			utils.ResponseError(c, 1, "未授权访问")
			c.Abort()
			return
		}

		// 检查是否以 Bearer 开头
		if !strings.HasPrefix(authHeader, "Bearer ") {
			utils.ResponseError(c, 1, "未授权访问")
			c.Abort()
			return
		}

		// 提取 token
		token := strings.TrimPrefix(authHeader, "Bearer ")

		uId := redisdb.GetUIdByTk(token)
		if uId == 0 {
			utils.ResponseError(c, 1, "未授权访问")
			c.Abort()
			return
		}
		// 先定义一个值,用于存user_id
		c.Set("user_id", uId)
		c.Next()
	}
}
